#include "systemtraymanager.h"
#include <QApplication>
#include <QDebug>
#include <QPixmap>
#include <QColor>
#include <QDir>

SystemTrayManager::SystemTrayManager(QObject *parent)
    : QObject(parent)
    , m_trayIcon(nullptr)
    , m_trayMenu(nullptr)
    , m_quitAction(nullptr)
{
    // 检查系统是否支持系统托盘
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        qWarning() << "系统不支持系统托盘";
        return;
    }

    qDebug() << "系统支持系统托盘，创建托盘图标";
    createTrayIcon();
    createTrayMenu();
    qDebug() << "托盘图标和菜单创建完成";
}

SystemTrayManager::~SystemTrayManager()
{
    if (m_trayIcon) {
        m_trayIcon->hide();
        delete m_trayIcon;
    }
    if (m_trayMenu) {
        delete m_trayMenu;
    }
}

void SystemTrayManager::createTrayIcon()
{
    m_trayIcon = new QSystemTrayIcon(this);
    
    // 设置托盘图标（使用 : 前缀，这是 C++ 中资源文件的正确格式）
    // 优先使用 logo.ico，如果不存在则尝试其他图标
    
    QIcon icon(":/icons/logo.ico");
    
    m_defaultIcon = icon;
    m_trayIcon->setIcon(icon);
    
    qDebug() << "托盘图标已设置，图标大小:" << icon.availableSizes();
    
    m_trayIcon->setToolTip("HiApp - 桌面端");

    // 连接托盘图标激活信号
    connect(m_trayIcon, &QSystemTrayIcon::activated, 
            this, &SystemTrayManager::onTrayIconActivated);
    
    // 注意：在 Windows 上，托盘图标需要先显示一次才能正常工作
    // 但这里我们不立即显示，而是在窗口最小化时才显示
    // 如果托盘图标在显示时出现问题，可能需要先显示然后隐藏来初始化
}

void SystemTrayManager::createTrayMenu()
{
    m_trayMenu = new QMenu();

    m_quitAction = new QAction("退出", this);
    connect(m_quitAction, &QAction::triggered, 
            this, &SystemTrayManager::onQuitActionTriggered);
    m_trayMenu->addAction(m_quitAction);

    m_trayIcon->setContextMenu(m_trayMenu);
}

void SystemTrayManager::showTrayIcon()
{
    if (m_trayIcon) {
        // 确保图标已设置
        if (m_trayIcon->icon().isNull()) {
            qWarning() << "托盘图标为空，重新设置图标";
            m_trayIcon->setIcon(m_defaultIcon);
        }
        
        m_trayIcon->show();
        qDebug() << "托盘图标已显示，是否可见:" << m_trayIcon->isVisible();
        emit trayVisibleChanged(true);
    } else {
        qWarning() << "托盘图标对象为空，无法显示";
    }
}

void SystemTrayManager::hideTrayIcon()
{
    if (m_trayIcon) {
        m_trayIcon->hide();
        emit trayVisibleChanged(false);
    }
}

void SystemTrayManager::setTrayVisible(bool visible)
{
    if (visible) {
        showTrayIcon();
    } else {
        hideTrayIcon();
    }
}

void SystemTrayManager::setTrayToolTip(const QString &tooltip)
{
    if (m_trayIcon) {
        m_trayIcon->setToolTip(tooltip);
    }
}

void SystemTrayManager::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    emit trayIconActivated(reason);
}

void SystemTrayManager::onQuitActionTriggered()
{
    emit quitRequested();
}

